<?php
/**
 * User: Drery
 * Date: 2015/11/18
 * Time: 17:16
 */

namespace api\components;

use yii\web\Response;

class ResponseHandler
{
    static public function beforeSender($event)
    {
        $response = $event->sender;
        if($response->data !== null) {
            $data = $response->data;
            if (is_string($data))
                return;
            if (!empty($data['file'])) {
                if (YII_DEBUG) {
                    return;
                } else {
                    $data['code'] = $data['status'] = 500;
                    unset($data['message']);
                }
            }
            if(!isset($data['code'])) {
                $response->data = [
                    'ret' => 0,
                    'message' => '',
                    'data' => $response->data
                ];
            }else{
                $response->data = [
                    'ret' => $data['code'] ? $data['code'] : ($data['status'] == 200 ? 0 : $data['status']),
                    'message' => !empty($data['message']) ? $data['message'] : self::generateResponseMessage($data['status']),
                    'data' => []
                ];
            }
            $response->statusCode = 200;
        }
    }

    static private function generateResponseMessage($code)
    {
        $maps = Response::$httpStatuses;
        return \Yii::t('api/error',$maps[$code]);
    }
}